package cn.xspace.module.other.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.LogUtils;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.StringUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.EditTextDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.module.other.R;
import cn.xspace.module.other.bean.FavoriteFolderBean;
import cn.xspace.module.other.adapter.FavoriteManagerAdapter;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MyFavoriteManagerActivity extends BaseActivity {

    private static final String TAG = MyFavoriteManagerActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private ExpandableListView mListView;

    private FavoriteManagerAdapter adapter;
    private List<FavoriteFolderBean> parentList = new ArrayList<>();
    private Map<String, List<FavoriteFolderBean>> childrenList = new HashMap<>();

    /**
     * 页面展示模式 0收藏文章 1收藏夹管理 2 移动收藏内容 3 移动文件夹
     */
    private int mode = 1; //默认为收藏夹管理
    private String title; //标题
    private String favorite_url; //地址
    private String sender_id; //发送方id
    private String msg_org; //来源
    private int msg_type; //类型
    private String user_id;
    private PopupWindow popupWindow;
    private String file_id;
    public static boolean isNeedRefresh = false;
    private String msg_deptid;
    private String folder_id;

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            queryAllFolder();
        }
    }

    @Override
    protected void getIntentData() {
        mode = getIntent().getIntExtra("mode", 0);
        title = getIntent().getStringExtra("webpage_title");
        favorite_url = getIntent().getStringExtra("favorite_url");
        sender_id = getIntent().getStringExtra("sender_id");
        msg_type = getIntent().getIntExtra("msg_type", 0);
        msg_org = getIntent().getStringExtra("msg_org");
        file_id = getIntent().getStringExtra("file_id");
        msg_deptid = getIntent().getStringExtra("msg_deptid");
        folder_id = getIntent().getStringExtra("folder_id");

        LogUtils.d("-------------------sender_id===" + sender_id);
        if (StringUtils.isNull(sender_id)) {
            sender_id = "";
        }
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_my_favorite_manager);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.favorite_manager_title);
        mTitleBar.setRightLayoutVisibility(View.GONE);
        mTitleBar.setTitle(ResourceUtils.getString(R.string.my_favorite_manager));
        mListView = (ExpandableListView) findViewById(R.id.favorite_webs_list_expandlv);
        if (mode == 0) {
            mTitleBar.setTitle(ResourceUtils.getString(R.string.save_my_favorite));
        } else if (mode == 1) {
            mTitleBar.setTitle(ResourceUtils.getString(R.string.my_favorite_manager));
        } else if (mode == 2) {
            mTitleBar.setTitle(ResourceUtils.getString(R.string.move_fav_art));
        } else if (mode == 3) {
            mTitleBar.setTitle(ResourceUtils.getString(R.string.move_fav_folder));
        }
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        refreshList();
        queryAllFolder();
    }

    private void refreshList() {
        if (adapter == null) {
            parentList.add(new FavoriteFolderBean(true));
            adapter = new FavoriteManagerAdapter(this, parentList, childrenList);
            mListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private void queryAllFolder() {
        showWaitDialog();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(RequestConstant.KEY_USER_ID, user_id);
        hashMap.put(RequestConstant.FOLDER_ID, null);
        OkHttpManager.getInstance().commonJsonPost(Constants.QueryFavoriteFolder, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            if ("0".equals(code)) {
                                JSONArray jsonArray = jsonObject.optJSONArray("folderList");
                                parseQueryAllFolder(jsonArray);
                            } else if ("3".equals(code)) {
                                hideWaitDialog();
                                parentList.clear();
                                parentList.add(new FavoriteFolderBean(true));
                                childrenList.clear();
                                refreshList();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 解析收藏夹的树结构
     *
     * @param jsonArray
     */
    private void parseQueryAllFolder(JSONArray jsonArray) {
        try {
            parentList.clear();
            childrenList.clear();
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject js = jsonArray.getJSONObject(i);
                    String folder_name = js.optString("folder_name");
                    String folder_id = js.optString("folder_id");
                    String isleaf = js.optString("isleaf");
                    List<FavoriteFolderBean> childlist_temp = new ArrayList<>();
                    if ("0".equals(isleaf)) {
                        JSONArray childListJS = js.optJSONArray("childList");
                        if (childListJS != null) {
                            for (int j = 0; j < childListJS.length(); j++) {
                                JSONObject jsj = childListJS.optJSONObject(j);
                                String folder_namej = jsj.optString("folder_name");
                                String folder_idj = jsj.optString("folder_id");
                                FavoriteFolderBean ffb_child = new FavoriteFolderBean(folder_namej, folder_idj, "0");
                                ffb_child.setParentId(folder_id);
                                childlist_temp.add(ffb_child);
                            }
                        }
                    }
                    FavoriteFolderBean addBean = new FavoriteFolderBean(true);
                    addBean.setParentId(folder_id);
                    childlist_temp.add(addBean);
                    childrenList.put(folder_id, childlist_temp);
                    FavoriteFolderBean ffb_temp = new FavoriteFolderBean(folder_name, folder_id, isleaf);
                    parentList.add(ffb_temp);
                }
                parentList.add(new FavoriteFolderBean(true));
                hideWaitDialog();
                refreshList();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        adapter.setiRightClickListener(new FavoriteManagerAdapter.IRightClickListener() {
            @Override
            public void onRightClick(View v, int mode, FavoriteFolderBean fwb, boolean isChild) {
                switch (mode) {
                    case 0://收藏
                        favoriteWebPage(fwb.getFolderId());
                        break;
                    case 1://更多
                        showPopUp(v, isChild, fwb);
                        break;
                    case 2: //移动收藏
//                        changeFavoriteFileFolder(fwb, file_id);
                        if (fwb.getFolderId().equals(folder_id)) {
                            T.showShort(mContext, "此文件夹下已收藏过此文章");
                        } else {
                            showChangeFavFolderDialog(fwb, file_id);
                        }
                        break;
                    case 3://移动收藏文件夹
                        break;
                }
            }

            @Override
            public void onAddClick(FavoriteFolderBean fwb) {
                showCreateFolderDialog(fwb.getParentId() + "");
            }
        });
    }

    /**
     * 新建收藏夹
     *
     * @param folder_name
     * @param folder_pid
     */
    public void createFolder(final String folder_name, String folder_pid) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_NAME, folder_name);
        map.put(RequestConstant.FOLDER_PARENT, folder_pid);
        OkHttpManager.getInstance().commonJsonPost(Constants.CreateFavoriteWebFolder, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            String desc = jsonObject.optString("desc");
                            if ("0".equals(code)) {
                                MyFavoriteActivity.isNeedRefresh = true;
                                if (mode == 0) { //收藏
                                    favoriteWebPage(desc);
                                } else if (mode == 2) { //移动
                                    changeFavoriteFileFolder(desc, folder_name, file_id);
                                } else {
                                    queryAllFolder();
                                }
                            } else {
                                hideWaitDialog();
                                T.showShort(mContext, desc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 删除收藏夹
     *
     * @param folder_id
     */
    public void deleteFolder(String folder_id) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_ID, folder_id);
        OkHttpManager.getInstance().commonJsonPost(Constants.DelFavoriteWebFolder, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            if ("0".equals(code)) {
                                MyFavoriteActivity.isNeedRefresh = true;
                                MyFavoriteActivity.isNeedReload = true;
                                queryAllFolder();
                            } else {
                                T.showShort(mContext, "删除失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 收藏
     *
     * @param folder_id
     */
    public void favoriteWebPage(String folder_id) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_ID, folder_id);
        map.put(RequestConstant.FILE_TITLE, title);
        map.put(RequestConstant.FILE_URL, favorite_url);
        map.put(RequestConstant.MSG_TYPE, msg_type);
        map.put(RequestConstant.MSG_ORG, msg_org);
        map.put(RequestConstant.SENDER_ID, sender_id);
        map.put(RequestConstant.MSG_DEPTID, msg_deptid);

        OkHttpManager.getInstance().commonJsonPost(Constants.AddFavoriteWeb, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            String desc = jsonObject.optString("desc");
                            if ("0".equals(code)) {
                                T.showShort(mContext, "收藏成功");
                                finish();
                            } else {
                                T.showShort(mContext, desc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 重命名收藏夹
     *
     * @param folder_id
     * @param folder_name
     */
    public void modifyFolderName(String folder_id, String folder_name) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_ID, folder_id);
        map.put(RequestConstant.FOLDER_NAME, folder_name);

        OkHttpManager.getInstance().commonJsonPost(Constants.MofifyFavoriteWebFolder, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            String desc = jsonObject.optString("desc");
                            if ("0".equals(code)) {
                                MyFavoriteActivity.isNeedRefresh = true;
                                queryAllFolder();
                            } else {
                                T.showShort(mContext, desc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 移动文章到指定收藏夹
     *
     * @param folder_id
     * @param folder_name
     * @param file_id
     */
    public void changeFavoriteFileFolder(String folder_id, final String folder_name, String file_id) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_ID, folder_id);
        map.put(RequestConstant.FILE_ID, file_id);

        OkHttpManager.getInstance().commonJsonPost(Constants.ChangeFavoriteFileFolder, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            String desc = jsonObject.optString("desc");
                            if ("0".equals(code)) {
                                MyFavoriteActivity.isNeedReload = true;
                                T.showShort(mContext, String.format(ResourceUtils.getString(R.string.move_fav_to),
                                        folder_name));
                                finish();
                            } else {
                                T.showShort(mContext, desc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 显示更多弹窗
     *
     * @param v
     * @param isChild
     * @param bean
     */
    private void showPopUp(View v, boolean isChild, final FavoriteFolderBean bean) {
        popDismiss();
        View contentView = View.inflate(mContext, R.layout.favorite_manager_folder_popup, null);
        TextView rename = (TextView) contentView.findViewById(R.id.tv_fav_pop_rename);
        TextView delete = (TextView) contentView.findViewById(R.id.tv_fav_pop_delete);
        TextView moveTo = (TextView) contentView.findViewById(R.id.tv_fav_pop_moveto);
        LinearLayout llMoveTo = (LinearLayout) contentView.findViewById(R.id.ll_show_move_to);
        if (!isChild) {
            llMoveTo.setVisibility(View.GONE);
        }
        rename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popDismiss();
                showRenameFolderDialog(bean);
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popDismiss();
                showDeleteDialog(bean);

            }
        });
        moveTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popDismiss();
                Intent intent = new Intent(MyFavoriteManagerActivity.this, MoveFavFolderActivity.class);
                intent.putExtra("folderId", bean.getFolderId());
                intent.putExtra("parentId", bean.getParentId());
                startActivity(intent);
            }
        });

        popupWindow = new PopupWindow(contentView, -2, -2, true);
        // 必须设置背景颜色,动画效果才会生效
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location = new int[2];
        v.getLocationInWindow(location);
        LogUtil.d(TAG, "wubaojie>>>onRightClick: iconHight:" + v.getMeasuredHeight());
        LogUtil.d(TAG, "wubaojie>>>onRightClick: iconRight:" + v.getMeasuredWidth() / 2);
        popupWindow.showAtLocation(v, Gravity.RIGHT + Gravity.TOP, v.getMeasuredWidth() / 2,
                location[1] + v.getMeasuredHeight());
    }

    /**
     * popupWindow的关闭方法
     */
    private void popDismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * 显示删除对话框
     *
     * @param bean
     */
    private void showDeleteDialog(final FavoriteFolderBean bean) {
        DialogHelp.getConfirmDialog(mContext,
                String.format(ResourceUtils.getString(R.string.delete_fav_folder), bean.getFolderName()),
                ResourceUtils.getString(R.string.delete_fav_folder_content),
                ResourceUtils.getString(R.string.think_again_and_again),
                ResourceUtils.getString(R.string.button_ok),
                null, new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        deleteFolder(bean.getFolderId());
                    }
                }).show();
    }

    /**
     * 显示移动对话框
     *
     * @param bean
     */
    private void showChangeFavFolderDialog(final FavoriteFolderBean bean, final String file_id) {
//        DialogHelp.getMessageDialog(mContext,
//                String.format(ResourceUtils.getString(R.string.move_fav_art_to), bean.getFolderName()), "",
//                ResourceUtils.getString(R.string.cancel),
//                ResourceUtils.getString(R.string.button_ok),
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }, null)
//                .show();
        new ConfirmDialog.Builder(mContext)
                .setTitleMsg(String.format(ResourceUtils.getString(R.string.move_fav_art_to), bean.getFolderName()))
                .setContentVisible(View.GONE)
                .setLeftText(ResourceUtils.getString(R.string.cancel))
                .setRightText(ResourceUtils.getString(R.string.button_ok))
                .setRightListener(new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        changeFavoriteFileFolder(bean.getFolderId(), bean.getFolderName(), file_id);
                    }
                })
                .setListener()
                .show();
    }

    /**
     * 显示重命名对话框
     *
     * @param bean
     */
    private void showRenameFolderDialog(final FavoriteFolderBean bean) {
//        final EditText editText = new EditText(mContext);
//        editText.setHint(R.string.no_more_than_8);
//        new AlertDialog.Builder(mContext)
//                .setTitle(R.string.rename_fav_folder)
//                .setView(editText)
//                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
//
//                    public void onClick(DialogInterface dialog, int which) {
//                        String name = editText.getText().toString();
//                        if (TextUtils.isEmpty(name) || name.length() > 8) {
//                            Toast.makeText(mContext, R.string.no_more_than_8, Toast.LENGTH_SHORT).show();
//                            return;
//                        } else {
//                            modifyFolderName(bean.getFolderId(), name);
//                        }
//                    }
//                }).setNegativeButton(R.string.cancel, null).show();
        final EditTextDialog dialog = new EditTextDialog.Builder(mContext, ResourceUtils.getString(R.string
                .rename_fav_folder)).build();
        dialog.setEtInputHint(R.string.no_more_than_8);
        dialog.setListener();
        dialog.setRightListener(new ButtonClickListener() {
            @Override
            public void buttonClick(View view) {
                String name = dialog.getText();
                if (TextUtils.isEmpty(name) || name.length() > 8) {
                    Toast.makeText(mContext, R.string.no_more_than_8, Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    modifyFolderName(bean.getFolderId(), name);
                }
            }
        });
        dialog.show();
    }

    /**
     * 显示新建文件夹对话框
     *
     * @param parent_id
     */
    private void showCreateFolderDialog(final String parent_id) {
//        final EditText editText = new EditText(mContext);
//        editText.setHint(R.string.no_more_than_8);
//        new AlertDialog.Builder(mContext)
//                .setTitle(R.string.create_new_folder)
//                .setView(editText)
//                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
//
//                    public void onClick(DialogInterface dialog, int which) {
//                        String newName = editText.getText().toString().trim();
//                        if (TextUtils.isEmpty(newName) || newName.length() > 8) {
//                            T.showShort(mContext, R.string.no_more_than_8);
//                            return;
//                        } else {
//                            createFolder(editText.getText().toString(), parent_id);
//                        }
//                    }
//                }).setNegativeButton(R.string.cancel, null).show();

        final EditTextDialog dialog = new EditTextDialog.Builder(mContext, ResourceUtils.getString(R.string
                .create_new_folder)).build();
        dialog.setEtInputHint(R.string.no_more_than_8);
        dialog.setListener();
        dialog.setRightListener(new ButtonClickListener() {
            @Override
            public void buttonClick(View view) {
                String newName = dialog.getText();
                if (TextUtils.isEmpty(newName) || newName.length() > 8) {
                    T.showShort(mContext, R.string.no_more_than_8);
                    return;
                } else {
                    createFolder(newName, parent_id);
                }
            }
        });
        dialog.show();

    }

    public int getMode() {
        return mode;
    }

    public void setMode(int mode) {
        this.mode = mode;
    }
}
